package goredis

import (
	"encoding/json"
	"time"
)

const (
	Serilizer_JSON = "json"
)

type DBGettFunc func() interface{}

type SimpleCache struct {
	Operation *StringOperation
	Expire    time.Duration
	DBGeter   DBGettFunc
	Serilizer string
}

func NewSimpleCache(operation *StringOperation, expire time.Duration, serilizer string) *SimpleCache {
	return &SimpleCache{Operation: operation, Expire: expire, Serilizer: serilizer}
}

//设置缓存
func (this *SimpleCache) SetCache(key string, value interface{}) {
	this.Operation.Set(key, value, WithExpire(this.Expire)).UnWrap()
}

//获取缓存
func (this *SimpleCache) GetCache(key string) (ret interface{}) {
	if this.Serilizer == Serilizer_JSON {
		//转成字符串
		f := func() string {
			if this.DBGeter == nil {
				return ""
			} else {
				obj := this.DBGeter()
				b, err := json.Marshal(obj)
				if err != nil {
					return ""
				}
				return string(b)
			}
		}
		ret = this.Operation.Get(key).UnwrapElse(f)
		this.SetCache(key, ret)
	}
	return
}

///锁
func (this *SimpleCache) Lock(key string, exp time.Duration) bool {
	return this.Operation.SetNx(key, 1, WithExpire(exp)).UnWrap().(bool)
}

//解锁
func (this *SimpleCache) Unlock(key string) {
	this.Operation.Del(key)
}

//删除缓存
func (this *SimpleCache) Del(key string) {
	this.Operation.Del(key)
}
